package com.ssy.lingxi.enhance.handler.exception;

import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 默认全局异常处理类，在所有异常处理类的最后
 * @author 万宁
 * @date 2020-05-29
 * @version 2.0.0
 */
@RestControllerAdvice
@Order(100)
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(feign.FeignException.class)
    public Wrapper<?> feignServiceException(HttpServletRequest request, feign.FeignException exception) {
        exception.printStackTrace();
        //请求路径 + 错误信息
        logger.error(exception.getMessage() == null ? request.getRequestURI().concat(" : ").concat(exception.getClass().getName()) : request.getRequestURI().concat(" : ").concat(exception.getMessage()));
        logger.error("", exception);
        return Wrapper.fail(ResponseCode.FEIGN_SERVICE_ERROR);
    }

    @ExceptionHandler(NullPointerException.class)
    public Wrapper<?> nullPointerException(HttpServletRequest request, NullPointerException exception) {
        exception.printStackTrace();
        //请求路径 + 错误信息
        logger.error(exception.getMessage() == null ? request.getRequestURI().concat(" : ").concat(exception.getClass().getName()) : request.getRequestURI().concat(" : ").concat(exception.getMessage()));
        return Wrapper.fail(ResponseCode.BUSINESS_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public Wrapper<?> validationBodyException(HttpServletRequest request, Exception exception) {
        exception.printStackTrace();
        //请求路径 + 错误信息
        logger.error(exception.getMessage() == null ? request.getRequestURI().concat(" : ").concat(exception.getClass().getName()) : request.getRequestURI().concat(" : ").concat(exception.getMessage()));
        return Wrapper.fail(ResponseCode.BUSINESS_ERROR);
    }
}
